package it.slkfarm.android;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import it.slkfarm.android.R;
import it.slkfarm.bean.Crop;
import it.slkfarm.bean.Farm;
import it.slkfarm.bean.Farmer;
import it.slkfarm.bean.Production;
import it.slkfarm.helpers.DialogBuilder;
import it.slkfarm.http.HttpConnector;
import it.slkfarm.log.LogData;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class Menu extends Base implements OnClickListener
{
	/**
	 * @uml.property  name="listOfStages"
	 * @uml.associationEnd  
	 */
	private JSONArray listOfStages;
	/**
	 * @uml.property  name="tl"
	 * @uml.associationEnd  
	 */
	private TableLayout tl;
	/**
	 * @uml.property  name="row"
	 * @uml.associationEnd  
	 */
	private TableRow row;
	/**
	 * @uml.property  name="tv"
	 * @uml.associationEnd  
	 */
	private TextView tv;
	/**
	 * @uml.property  name="welcome"
	 * @uml.associationEnd  
	 */
	private TextView welcome;
	/**
	 * @uml.property  name="currentFarm"
	 * @uml.associationEnd  
	 */
	private TextView currentFarm;
	/**
	 * @uml.property  name="tf"
	 * @uml.associationEnd  
	 */
	private Typeface tf;
	/**
	 * @uml.property  name="button"
	 * @uml.associationEnd  
	 */
	private Button button;
	/**
	 * @uml.property  name="change"
	 * @uml.associationEnd  
	 */
	private Button change;
	/**
	 * @uml.property  name="logout"
	 * @uml.associationEnd  
	 */
	private Button logout;
	/**
	 * @uml.property  name="intent"
	 * @uml.associationEnd  
	 */
	private Intent intent;
	/**
	 * @uml.property  name="builder"
	 * @uml.associationEnd  
	 */
	private DialogBuilder builder;
	/**
	 * @uml.property  name="progress"
	 * @uml.associationEnd  readOnly="true"
	 */
	private Dialog progress;
	/**
	 * @uml.property  name="dialog"
	 * @uml.associationEnd  
	 */
	private Dialog dialog;
	/**
	 * @uml.property  name="farmer"
	 * @uml.associationEnd  
	 */
	private Farmer farmer;
	/**
	 * @uml.property  name="farm"
	 * @uml.associationEnd  
	 */
	private Farm farm;

	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
		setLanguage(dbAdapter.getSetLanguage());
		builder = new DialogBuilder(this, dbAdapter.getSetLanguage());
		tf = getTypeface();
		Intent i = getIntent();
		farmer = (Farmer) i.getSerializableExtra(getPackageName() + ".farmer");
		farm = (Farm) i.getSerializableExtra(getPackageName() + ".farm");
        setContentView(R.layout.menu);
        tl = (TableLayout) findViewById(R.id.tlMenu2);
        tv = (TextView) findViewById(R.id.tvMenuTitle);
        tv.setTypeface(tf);
        logout = (Button) findViewById(R.id.btnMenuLogout);
        logout.setTypeface(tf);
        logout.setOnClickListener(this);
        change = (Button) findViewById(R.id.btnChangeFarm);
        change.setTypeface(tf);
        change.setOnClickListener(this);
        welcome = (TextView) findViewById(R.id.tvWelcomeFarmer);
        welcome.setTypeface(tf);
        welcome.setText(welcome.getText() + " " + farmer.getFirstname() + " " + farmer.getLastname());
        currentFarm = (TextView) findViewById(R.id.tvCurrentFarm);
        currentFarm.setTypeface(tf);
        currentFarm.setText(currentFarm.getText() + " " + farm.getName());
        createMenu();
    }
	
	public void onResume()
	{
		super.onResume();
		Log.i("menu", "resume");
	}
	
	private void createMenu()
	{	
		HttpConnector connector = new HttpConnector();
		try 
		{
			if (connector.connect(WEB_SERVICE_URL_STAGES, null) == 200)
			{
				JSONObject menu = connector.getJson();
				listOfStages = menu.getJSONArray("Stages");
				int i=0;
				while (i<listOfStages.length())
				{
					row = new TableRow(this);
					TableLayout.LayoutParams tableRowParams=new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
					tableRowParams.setMargins(0, 7, 0, 0);
					row.setLayoutParams(tableRowParams);
					JSONObject app = listOfStages.getJSONObject(i);
					button = new Button(this);
					if (i>=1)
					{
						button.setBackgroundResource(R.drawable.button_disabled);
						button.setEnabled(false);
					}
					else
					{
						button.setBackgroundResource(R.drawable.button);
						button.setEnabled(true);
					}
					button.setTextColor(Color.parseColor("#43520B"));
					if (dbAdapter.getSetLanguage() == SRI_LANG)
					{
						String title = app.getString("Sinhala Name");
						button.setText(title);
						button.setTypeface(tf);
					}
					else
					{
						button.setText(app.getString("name"));
						button.setTypeface(tf);
					}
					button.setId(200 + app.getInt("id"));
					button.setOnClickListener(this);
					row.addView(button);	
					i++;
					tl.addView(row);
				}
			}
		} 
		catch (ClientProtocolException e1) 
		{
			e1.printStackTrace();
		} 
		catch (IOException e1) 
		{
			e1.printStackTrace();
		} 
		catch (IllegalStateException e) 
		{
			e.printStackTrace();
		} 
		catch (JSONException e) 
		{
			e.printStackTrace();
		}
		
	}
	
	
	public void onClick(View v) 
	{
		if (v.getId() == change.getId())
		{
			List<Farm> farmList = dbAdapter.getFarmList(farmer.getId());
			if (farmList.size() == 1)
			{
				Toast t = builder.createToast(R.string.one_farm, null, Menu.this);
				t.show();
			}
			else
			{
				dialog = builder.createChangeFarmDialog(farmList, Menu.this);
				dialog.show();
				dialog.setOnDismissListener(new OnDismissListener() 
				{
					public void onDismiss(DialogInterface arg0) 
					{
						farm = builder.getFarmChange();
						currentFarm.setText(R.string.current_farm);
						currentFarm.setText(currentFarm.getText() + " " + farm.getName());
					}
				});
			}
		}
		
		
		if (v.getId() == R.id.btnMenuLogout)
		{
			LogData log = new LogData("Menu","Button logout","Logout");
			logger.appendLog(log);
			Intent intent = new Intent(Menu.this, Login.class);
			startActivity(intent);
			finish();
		}
		else if (v.getId() == 201)
		{
			intent = new Intent(Menu.this, CropTabView.class);
			intent.putExtra(getPackageName() + ".farm", farm);
			intent.putExtra(getPackageName() + ".lang", dbAdapter.getSetLanguage());
			intent.putExtra(getPackageName() + ".secretKey", farmer.getSecretKey());
			startActivity(intent); 
		}
		
	}
}
